﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using nHydrate.Dsl;

namespace nHydrate.DslPackage.Forms
{
	public partial class RefactorPreviewChangeNTextForm : Form
	{
		private Microsoft.VisualStudio.Modeling.Store _store = null;
		private List<Entity> _entityList = null;

		public RefactorPreviewChangeNTextForm()
		{
			InitializeComponent();
		}

		public RefactorPreviewChangeNTextForm(Microsoft.VisualStudio.Modeling.Store store, List<Entity> entityList)
			: this()
		{
			_store = store;
			_entityList = entityList;

			foreach (var entity in _entityList)
			{
				foreach (var field in entity.Fields.Where(x => x.DataType == DataTypeConstants.NText || x.DataType == DataTypeConstants.Text))
				{
					lstItem.Items.Add(new DisplayItem() { Field = field });
					lstItem.SetItemChecked(lstItem.Items.Count - 1, true);
				}
			}

			this.DoShow = (lstItem.Items.Count > 0);
		}

		public bool DoShow { get; private set; }

		private void cmdApply_Click(object sender, EventArgs e)
		{
			//Change the types
			using (var transaction = _store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
			{
				foreach (DisplayItem di in lstItem.CheckedItems)
				{
					if (di.Field.DataType == DataTypeConstants.NText)
					{
						di.Field.DataType = DataTypeConstants.NVarChar;
						di.Field.Length = 0;
					}
					else if (di.Field.DataType == DataTypeConstants.Text)
					{
						di.Field.DataType = DataTypeConstants.VarChar;
						di.Field.Length = 0;
					}
				}
				transaction.Commit();
			}

			this.DialogResult = System.Windows.Forms.DialogResult.OK;
			this.Close();
		}

		private void cmdCancel_Click(object sender, EventArgs e)
		{
			this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.Close();
		}

		private class DisplayItem
		{
			public Field Field { get; set; }

			public override string ToString()
			{
				return this.Field.Entity.Name + "." + this.Field.Name;
			}
		}
	}
}
